<template>
  <div class="">
    {{ newFormId }} -{{ newRecordId }}-{{ iframeUrl }}
    <div class="iframe-form-wrap">
      <div
        class="iframe-box"
        :style="{ width: '100%', height: `calc(100vh - ${topBarHeight + 120}px)` }"
      >
        <!-- <iframe
          v-if="iframeUrl"
          ref="childIframe"
          :src="iframeUrl"
          frameborder="no"
          :style="{ width: 'calc(100% + 19px)', height: '100%' }"
          scrolling="auto"
        ></iframe> -->
      </div>
    </div>
  </div>
</template>

<script setup>
  import {
    computed,
    defineExpose,
    getCurrentInstance,
    nextTick,
    onBeforeUnmount,
    onMounted,
    ref,
    watch,
  } from 'vue';
  import { onBeforeRouteLeave } from 'vue-router';
  import { getToken } from '@/utils/auth';
  import { getIframeUrl } from '@/utils/iframeConfig';
  import {
    getVersionList,
    getDocumentDetail,
    getProperties,
    updateForm,
    documentPublish,
    getPresetFields,
    updatePresetFields,
  } from '@/api/docReport/index.js';
  import { initMessage, removeMessage, sendMsgToChild } from '@/utils/iframe';
  import { postSubmit } from '@/api/handbookRecord/index';
  // import { load } from '@/utils/loading';

  const props = defineProps({
    recordId: {
      type: [Number, String],
      default: '',
    },
    formId: {
      type: [Number, String],
      default: '',
    },
    viewModel: {
      type: String,
      default: 'view',
    },
    bizModule: {
      type: String,
      default: '',
    },
  });
  const emit = defineEmits(['saveFormData']);
  const { proxy } = getCurrentInstance();

  const topBarHeight = ref(0);
  const iframeHeight = ref(document.documentElement.clientHeight - 60 + 'px');

  const newFormId = ref(props.formId);
  const newRecordId = ref(props.recordId);

  const token = getToken();
  const iframeUrl = computed(() => {
    return `${getIframeUrl() + props.viewModel}?documentInfoId=${
      newFormId.value
    }&token=${token}&bizModule=${props.bizModule}`;
  });
  const showIframe = ref(false);
  const childIframe = ref(null);
  function sendInitData() {
    let params = {};
    sendMsgToChild(childIframe.value, params);
  }
  const postMsg = ({ type, data }) => {
    if (!childIframe.value) return;
    childIframe.value.contentWindow.postMessage({ type, data }, '*');
  };
  function handleIframeMessage() {
    initMessage(async (params) => {
      if (params?.type) {
        const { type, data: msgData } = params;
        switch (type) {
          // 文档详情
          case 'getDocumentDetail':
            // 文档详情  /document/detail\

            try {
              const data = await getDocumentDetail({
                documentInfoId: msgData.documentInfoId,
                documentId: msgData.documentId,
                bizModule: props.bizModule,
              });
              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;
          case 'getProperties':
            // 报告可选字段列表
            try {
              const data = await getProperties();
              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;
          case 'getVersionList':
            // 版本列表
            try {
              const data = await getVersionList(newFormId.value);
              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;

          case 'documentUpdate':
            // 保存草稿/暂存
            try {
              let data = await updateForm({
                ...msgData,
                bizModule: props.bizModule, //模块名称固定为AdverseEventReport
                attribute: {
                  id: msgData.documentId,
                },
              });
              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;
          case 'documentPublish':
            // 发布
            try {
              let data;
              if (props.bizModule === 'NursingHandbook') {
                data = await documentPublish({
                  ...msgData,
                  bizModule: props.bizModule, //模块名称固定为AdverseEventReport
                  attribute: {
                    id: msgData.documentId,
                  },
                  usable: true,
                });
              } else {
                data = await postSubmit({
                  documentDto: {
                    ...msgData,
                    bizModule: props.bizModule, //模块名称固定为AdverseEventReport
                    attribute: {
                      id: msgData.documentId,
                    },
                    usable: true,
                  },
                  id: newRecordId.value,
                });
                if (data?.code === 200) {
                  emit('saveFormData', { id: newRecordId.value });
                }
              }

              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;
          case 'goBack':
            postMsg(type, {});

            // 报告可选字段列表
            break;
          case 'getPresetFields':
            // 获取表单上报时需要进行通信的字段
            try {
              const data = await getPresetFields();
              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;
          case 'updatePresetFields':
            // 发布表单字段说明与编码
            try {
              const data = await updatePresetFields(msgData);
              postMsg({ type, data });
            } catch (error) {
              console.error(error);
            }
            break;
          default:
            break;
        }
      }
    });
  }

  function handleReceiveData(params) {}
  function getIframeCallBack(params) {
    return params;
  }

  function showTips(msg = '') {
    proxy.$message.success(msg);
  }
  function saveForm(callBack) {}

  async function handleIframeDataLoad() {
    sendInitData();
  }
  function clearIframeCacheData(next) {
    postMsg({ type: 'clearCache', data: {} });

    setTimeout(() => {
      next && next();
    });
  }

  defineExpose({
    saveForm,
    handleIframeMessage,
    getIframeCallBack,
  });
  onMounted(async () => {
    handleIframeMessage();
  });
  // 监听fromId变化和recordId并修改表单内容
  watch(
    [() => props.formId, () => props.recordId],
    async ([newUpdateFormId, newUpdateRecordId, newViewModel]) => {
      if (newUpdateRecordId) {
        newRecordId.value = newUpdateRecordId;
      }

      if (newUpdateFormId) {
        newFormId.value = newUpdateFormId;
        await nextTick();
        handleIframeDataLoad();
      }
    },
  );

  onBeforeUnmount(() => {
    removeMessage();
  });
  onBeforeRouteLeave((to, from, next) => {
    clearIframeCacheData(next);
  });
</script>

<style lang="scss" scoped>
  .iframe-form-wrap {
    .iframe-box {
      overflow: hidden;
    }
  }
</style>
